package com.tmptSource.service.impl;

import com.tmpt.dto.Result;
import com.tmpt.utils.DateTool;
import com.tmpt.service.impl.DataLimitService;
import com.tmpt.utils.JsonPaginationUtils;
import com.tmpt.utils.StringUtils;
import com.tmpt.utils.WebUtils;
import com.tmptSource.bean.*;
import com.tmptSource.dto.*;
import com.tmptSource.enums.OwTaskType;
import com.tmptSource.mapper.*;
import com.tmptSource.service.intf.*;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tmptSource.utils.dozer.MyMapper;
import com.tmptSource.utils.page.MyPageUtils;

import java.text.SimpleDateFormat;
import java.util.*;

import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.log4j.Logger;

import javax.annotation.Resource;

/**
 * Created by wxy on 2016/7/28.
 */
@Service(value = "owrTmpPairService")
@Transactional(propagation = Propagation.REQUIRED)
public class OwrTmpPairService implements IOwrTmpPairService {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private DataLimitService dataLimitService;
    @Autowired
    private IOwrDoubleTaskPairService owrDoubleTaskPairService;
    @Autowired
    private Mapper mapper;
    @Autowired
    private MyMapper myMapper;
    @Autowired
    private MyPageUtils myPageUtils;
    @Autowired
    private OwrTmpPairMapper owrTmpPairMapper;
    @Autowired
    private A2userMapper a2userMapper;
    @Autowired
    private OwrTmpEntityMapper owrTmpEntityMapper;
    @Autowired
    private OwrEntityListInfoMapper owrEntityListInfoMapper;
    @Autowired
    private OwrDoubleTaskPairMapper owrDoubleTaskPairMapper;
    @Autowired
    private OwrRegionMapper owrRegionMapper;
    @Autowired
    private OwrTypeMapper owrTypeMapper;
    @Autowired
    private IOwTaskService owTaskService;
    @Autowired
    private IOwNumberInfoService owNumberInfoService;
/*

    private String year = DateTool.getCurrentDateStr1("yyyy");
    private String month = getCurrentMonth();
    private String quarter = getCurrentQuarter();

*/

/*
    private String year = "2018";
    private String month = "12";
    private String quarter = "Q4";
*/


    /**
     * 双随机-工地生成任务清单-手动
     * @param owrDoubleTaskPairDto
     * @return
     */
    @Override
    public Result exeBuildingQuartz(OwrDoubleTaskPairDto owrDoubleTaskPairDto){
        Result<OwrDoubleTaskPairDto> result = new Result();
        owrDoubleTaskPairDto.setOwrType("1");
        //校验
        int count = selectCount(owrDoubleTaskPairDto);
        if(count>0){
            return result.fault("请不要重复生成任务清单");
        }else{
            List<OwrRegion> owrRegions = owrRegionMapper.selectAllRegionId();

            //工地 : owrTypeId 1,工地，2 餐厨
            for (int i = 0; i < owrRegions.size(); i++) {
                OwrRegion owrRegion = owrRegions.get(i);
                Long owrTypeId = owrRegion.getOwrTypeId();
                OwrType owrType = owrTypeMapper.selectById(owrTypeId);
                if(owrTypeId != 1){
                    continue;
                }
                Result result1 = execute1(owrDoubleTaskPairDto,owrRegion, owrType);
                if(!result1.isSuccess()){
                    if("continue".equals(result1.getContent())){
                        continue;
                    }
                }
        }

    }
        return result.success();
}

    public int selectCount(OwrDoubleTaskPairDto OwrDoubleTaskPairDto) {
        OwrDoubleTaskPair owrDoubleTaskPair = mapper.map(OwrDoubleTaskPairDto,OwrDoubleTaskPair.class);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("bean", owrDoubleTaskPair);
        int count = owrDoubleTaskPairMapper.selectListCount(paramMap);
        return count;
    }

    /**
     * 双随机-餐厨生成任务清单-手动
     * @param owrDoubleTaskPairDto
     * @return
     */
    @Override
    public Result exeKitchenQuartz(OwrDoubleTaskPairDto owrDoubleTaskPairDto){
        Result<OwrDoubleTaskPairDto> result = new Result();

        owrDoubleTaskPairDto.setOwrType("2");
        //校验
        int count = selectCount(owrDoubleTaskPairDto);
        if(count>0){
            return result.fault("请不要重复生成任务清单");
        }else{
            List<OwrRegion> owrRegions = owrRegionMapper.selectAllRegionId();
            //在执行之前先检查本年度本季度是否已经执行过，如果已经执行过，把所有的记录伪删除 deleteflag=1
//        deleteAllKitchBuilding(year,currentQuarter,currentMonth,"SYSTEM");

            //餐厨 : owrTypeId 1,工地，2 餐厨
            for (int i = 0; i < owrRegions.size(); i++) {
                OwrRegion owrRegion = owrRegions.get(i);
                Long owrTypeId = owrRegion.getOwrTypeId();
                OwrType owrType = owrTypeMapper.selectById(owrTypeId);
                if(owrTypeId != 2){
                    continue;
                }
                Result result1 = execute2(owrDoubleTaskPairDto,owrRegion, owrType);
                if(!result1.isSuccess()){
                    if("continue".equals(result1.getContent())){
                        continue;
                    }
                }
            }

        }


        return result.success();
    }

    /**
     * 双随机-餐厨工地派发任务清单-手动
     * 启动一个线程，让它自己执行，然后可以立马返回前端消息new Result().success("kkkkkkk");
     * @param owrDoubleTaskPairDto
     * @return
     */

    @Override
    public Result sendToTask(OwrDoubleTaskPairDto owrDoubleTaskPairDto) {
        //启动一个匿名线程
        new Thread(){
            @Override
            public void run() {
                sendToTaskInner(owrDoubleTaskPairDto);
            }
        }.start();
        return new Result().success("任务正在派发，可能需要几分钟的时间，请耐心等待后查询列表页面，不要编辑或者重复派发任务！");
    }

    public Result sendToTaskInner(OwrDoubleTaskPairDto owrDoubleTaskPairDto) {
        Result<OwrDoubleTaskPairDto> result = new Result();
        String year = owrDoubleTaskPairDto.getYear();
        String month = owrDoubleTaskPairDto.getMonth();
        String quarter = owrDoubleTaskPairDto.getQuarter();
        //查询出符合条件的餐厨任务清单

        //查询条件
        OwrDoubleTaskPair owrDoubleTaskPair = new OwrDoubleTaskPair();
        owrDoubleTaskPair.setYear(year);
        owrDoubleTaskPair.setQuarter(quarter);
        owrDoubleTaskPair.setMonth(month);
        //默认类型餐厨
        owrDoubleTaskPair.setOwrType(Integer.parseInt(owrDoubleTaskPairDto.getOwrType()));
        //只查询出没有派发任务的记录，taskID=0
        owrDoubleTaskPair.setOwTaskId(0L);

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("page",pageDto);
        mapParam.put("bean",owrDoubleTaskPair);

//        String start = DateTool.getCurrentDateStr1("yyyyMMddHHmmssSSS");
        List<OwrDoubleTaskPair> list = owrDoubleTaskPairMapper.selectAll(mapParam);
//        String over = DateTool.getCurrentDateStr1("yyyyMMddHHmmssSSS");
//        String recycle = DateTool.getCurrentDateStr1("yyyyMMddHHmmssSSS");

//        List<String> listStart = new ArrayList<>();
        //循环
        for (OwrDoubleTaskPair pair:list){
            //involve task 触发任务，抽取出来
//            String time = DateTool.getCurrentDateStr1("yyyyMMddHHmmssSSS");
//            listStart.add(time);
            Result<OwTaskDto> resultTask = send2Task(pair);
            OwTaskDto owTaskDtoReturn = resultTask.getResultObj();
            String owTaskId = owTaskDtoReturn.getId();
            //插入taskID，任务派发成功
            pair.setOwTaskId(Long.parseLong(owTaskId));
            pair.setModifymanId(Integer.parseInt(owrDoubleTaskPairDto.getModifymanId()));
            pair.setModifyman(owrDoubleTaskPairDto.getModifyman());
            pair.setCompanyId(Integer.parseInt(owrDoubleTaskPairDto.getCompanyId()));

            //更新记录
            owrDoubleTaskPairMapper.updateById(pair);
        }

//        String finish=DateTool.getCurrentDateStr1("yyyyMMddHHmmssSSS");
//        System.out.println("查询任务清单开始："+start);
//        System.out.println("查询任务清单结束："+over);
//        System.out.println("循环开始："+recycle);
//        for (int i=0;i<listStart.size();i++){
//            System.out.println(listStart.get(i));
//        }
//        System.out.println("循环结束："+finish);
        return result.success();
    }

    /**
     * 工地
     * @param owrRegion
     * @return
     */
    private Result execute1(OwrDoubleTaskPairDto owrDoubleTaskPairDto, OwrRegion owrRegion, OwrType owrType){
        Result result = new Result();

        String year = owrDoubleTaskPairDto.getYear();
        String month = owrDoubleTaskPairDto.getMonth();
        String quarter = owrDoubleTaskPairDto.getQuarter();

        Long owrRegionId = owrRegion.getId();
        String regionName = owrRegion.getRegionName();
        Long owrTypeId = owrType.getId();
        String owrTypeName = owrType.getTypeName();

        //执行工地策略
        //query entity by region
        Map paramMap = new HashMap();
        OwrEntityListInfo owrEntityListInfoParam = new OwrEntityListInfo();
        owrEntityListInfoParam.setOwrRegionId(owrRegionId); //query by region id
        owrEntityListInfoParam.setOwrType(Integer.parseInt(owrTypeId.toString()));
        paramMap.put("bean", owrEntityListInfoParam);

        List<OwrEntityListInfo> owrEntityListInfoList = owrEntityListInfoMapper.selectAll(paramMap);

        //根据区域查出有多少工地query count of entity by region
        int entityCountByRegion = owrEntityListInfoList.size();

        //给工作人员分组 ，有多少工地就分多少组divide user to pair group = entityCountByRegion
        List<A2user> userList = a2userMapper.selectOwrByRegionId(owrRegionId);

        //users to pairlist
        List<OwrTmpPair> owrTmpPairList = new ArrayList<>();
        exePair(year,quarter,month,owrRegionId, entityCountByRegion, userList, owrTmpPairList);

        //entity and userpair to temp table, owrEntityListInfoList and owrTmpPairList -> owrTmpEntityList
        List<OwrTmpEntity> owrTmpEntityList = new ArrayList<>();
        String createman = exeOwrTmpEntity(year,quarter,month,owrRegionId, regionName, owrEntityListInfoList, owrTmpPairList, owrTmpEntityList);

        //new requirement: not combine the entity. a task each entity.
        //query  通过createman，查出合并后的排班计划集合
        //combine repeat data,createman的值是当前时间精确到毫秒的值，查询当前执行的一批记录
        //List<OwrTmpEntity> owrTmpEntityListNorepeat = owrTmpEntityMapper.selectPairPlanByCreateman(createman);

        //获取配对信息后，进行数据插入
        for (OwrTmpEntity owrTmpEntity : owrTmpEntityList) {
            OwrDoubleTaskPair owrDoubleTaskPair = new OwrDoubleTaskPair();
            //封装数据
            owrDoubleTaskPair.setCreatemanId(0);
            owrDoubleTaskPair.setCreateman("SYSTEM");
            owrDoubleTaskPair.setCompanyId(1);
            owrDoubleTaskPair.setCreatedate(DateTool.getCurTimestamp());
            //插入数据
            owrDoubleTaskPair.setOwrRegionId(owrTmpEntity.getRegionId());
            owrDoubleTaskPair.setRegionName(owrTmpEntity.getRegionName());
            //工地存储当前月
            owrDoubleTaskPair.setYear(year);
            owrDoubleTaskPair.setQuarter(quarter);
            owrDoubleTaskPair.setMonth(month);
            owrDoubleTaskPair.setOwrType(Integer.parseInt(owrTypeId.toString()));
            owrDoubleTaskPair.setOwrTypeName(owrTypeName);
            owrDoubleTaskPair.setUserId(owrTmpEntity.getUserPair());
            owrDoubleTaskPair.setEntityId(owrTmpEntity.getEntityId());
            owrDoubleTaskPair.setUserName(owrTmpEntity.getUserNamePair());
            owrDoubleTaskPair.setEntityName(owrTmpEntity.getEntityName());
            OwrEntityListInfo entityListInfo = owrEntityListInfoMapper.selectById(Long.parseLong(owrTmpEntity.getEntityId()));
            owrDoubleTaskPair.setOwrEntityListInfo(entityListInfo);

            //调用mapper
            //TaskId默认是0，表示还没有派发任务
            owrDoubleTaskPair.setOwTaskId(0L);
            owrDoubleTaskPairMapper.insert(owrDoubleTaskPair);
        }

        return result.success();
    }

    /**
     * 餐厨
     * @param owrRegion
     * @param owrType
     * @return
     */
    private Result execute2(OwrDoubleTaskPairDto owrDoubleTaskPairDto,OwrRegion owrRegion, OwrType owrType){
        Result result = new Result();

        String year = owrDoubleTaskPairDto.getYear();
        String month = owrDoubleTaskPairDto.getMonth();
        String quarter = owrDoubleTaskPairDto.getQuarter();

        Long owrRegionId = owrRegion.getId();
        String regionName = owrRegion.getRegionName();
        Long owrTypeId = owrType.getId();
        String owrTypeName = owrType.getTypeName();
        //执行餐厨策略，每个季度生成一次， 一家店招必须分配两个队员检查，每季度覆盖25%，当年抽查过的就不用再抽了
        Map paramMap = new HashMap();
        OwrEntityListInfo owrEntityListInfoParam = new OwrEntityListInfo();
        owrEntityListInfoParam.setOwrRegionId(owrRegionId); //query by region id
        owrEntityListInfoParam.setOwrType(Integer.parseInt(owrTypeId.toString()));
        paramMap.put("bean", owrEntityListInfoParam);
        paramMap.put("year",year);
        List<OwrEntityListInfo> owrEntityListInfoList = owrEntityListInfoMapper.selectAllExceptBefore(paramMap);
        List<OwrEntityListInfo> owrEntityListInfoListResult = new ArrayList<>();
        //query count of entity by region 第一季度抽取四分之一，第二季度抽取剩下的里面的三分之一，
        // 第三季度，抽取二分之一，最后的抽取剩下所有的
        int entityCountByRegion = owrEntityListInfoList.size();
        if(entityCountByRegion==0){
            return result.fault("continue");
        }
        int randomNum = 0 ;
        switch (quarter) {
            case "Q1":
                randomNum = entityCountByRegion/4 ;
                break;
            case "Q2":
                randomNum = entityCountByRegion/3 ;
                break;
            case "Q3":
                randomNum = entityCountByRegion/2 ;
                break;
            case "Q4":
                randomNum = entityCountByRegion;;
                break;
        }
        Set randomSetNotRepeat = new HashSet();
        //when set have the repeat index, eg: 5,3,6,8,5,5,4,3,2,,9,10,5   ??????????????????????????

        //第四季度的时候，所有没有检查过得餐厨都要检查
        if("Q4".equals(quarter)){
            owrEntityListInfoListResult = owrEntityListInfoList;
        }else{
            //获取随机randomNum set
            randomSetNotRepeat = getRandomSetNotRepeat(entityCountByRegion, randomNum);
        }

        Iterator<Integer> iterator = randomSetNotRepeat.iterator();
        while(iterator.hasNext()){
            int index = iterator.next();
            owrEntityListInfoListResult.add(owrEntityListInfoList.get(index));
        }

        //根据区域id获得检查人员列表 divide user to pair group = entityCountByRegion
        List<A2user> userList = a2userMapper.selectOwrByRegionId(owrRegionId);

        //给检查人员分组 users to pairlist 总共有randomNum组
        List<OwrTmpPair> owrTmpPairList = new ArrayList<>();
        exePair(year,quarter,month,owrRegionId, randomNum, userList, owrTmpPairList);

        //将检查人员和实体表对应插入到临时表entity and userpair to temp table, owrEntityListInfoList and owrTmpPairList -> owrTmpEntityList
        List<OwrTmpEntity> owrTmpEntityList = new ArrayList<>();
        String createman = exeOwrTmpEntity(year,quarter,month,owrRegionId, regionName, owrEntityListInfoListResult, owrTmpPairList, owrTmpEntityList);

        //new requirement: not combine the entity. a task each entity.
        //query  通过createman，查出合并后的排班计划集合//combine repeat data,createman的值是当前时间精确到毫秒的值，查询当前执行的一批记录
        //List<OwrTmpEntity> owrTmpEntityListNorepeat = owrTmpEntityMapper.selectPairPlanByCreateman(createman);

        //获取配对信息后，进行数据插入
        //System.out.println("owrTmpEntityListNorepeat ssssize:" + owrTmpEntityListNorepeat.size());
        for (OwrTmpEntity owrTmpEntity : owrTmpEntityList) {
            OwrDoubleTaskPair owrDoubleTaskPair = new OwrDoubleTaskPair();
            owrDoubleTaskPair.setCreatemanId(0);
            owrDoubleTaskPair.setCreateman("SYSTEM");
            owrDoubleTaskPair.setCompanyId(0);
            owrDoubleTaskPair.setCreatedate(DateTool.getCurTimestamp());
            //插入数据
            owrDoubleTaskPair.setOwrRegionId(owrTmpEntity.getRegionId());
            owrDoubleTaskPair.setRegionName(owrTmpEntity.getRegionName());
            owrDoubleTaskPair.setYear(year);
            owrDoubleTaskPair.setQuarter(quarter);
            owrDoubleTaskPair.setMonth(month);
            owrDoubleTaskPair.setOwrType(Integer.parseInt(owrTypeId.toString()));
            owrDoubleTaskPair.setOwrTypeName(owrTypeName);
            owrDoubleTaskPair.setUserName(owrTmpEntity.getUserNamePair());
            owrDoubleTaskPair.setEntityName(owrTmpEntity.getEntityName());
            owrDoubleTaskPair.setUserId(owrTmpEntity.getUserPair());
            owrDoubleTaskPair.setEntityId(owrTmpEntity.getEntityId());
            OwrEntityListInfo entityListInfo = owrEntityListInfoMapper.selectById(Long.parseLong(owrTmpEntity.getEntityId()));
            owrDoubleTaskPair.setOwrEntityListInfo(entityListInfo);
            //involve task
            //调用mapper
            //TaskId默认是0，表示还没有派发任务
            owrDoubleTaskPair.setOwTaskId(0L);
            owrDoubleTaskPairMapper.insert(owrDoubleTaskPair);
        }

        return result.success();
    }

    /**
     *involve task method 派发任务方法
     */
    private Result<OwTaskDto> send2Task(OwrDoubleTaskPair owrDoubleTaskPair){
        //gen number
        OwNumberInfoDto owNumberInfoDtoParam = new OwNumberInfoDto();
        owNumberInfoDtoParam.setCompanyId("1");
        Result resultNumber = owNumberInfoService.addData(owNumberInfoDtoParam);

        OwNumberInfoDto owNumberInfoDto = (OwNumberInfoDto)resultNumber.getResultObj();
        OwTaskDto owTaskDto = new OwTaskDto();
        owTaskDto.setTaskNumber(owNumberInfoDto.getNumber());
        owTaskDto.setName("巡视："+owrDoubleTaskPair.getEntityName());
        owTaskDto.setMainManId(owrDoubleTaskPair.getUserId());
        owTaskDto.setMainManName(owrDoubleTaskPair.getUserName());
        owTaskDto.setOwPriorityCode("1");
        owTaskDto.setOwViolationType("5");
        owTaskDto.setPosDesc(owrDoubleTaskPair.getOwrEntityListInfo().getEntAddr());
        owTaskDto.setLitigantName(owrDoubleTaskPair.getOwrEntityListInfo().getEntRespPerson());
        owTaskDto.setLitigantPhone(owrDoubleTaskPair.getOwrEntityListInfo().getEntTel());
        switch (owrDoubleTaskPair.getOwrType()){
            case 1://building
                owTaskDto.setOwRegisterType("3");
                owTaskDto.setIssueContent("建筑工地、中转码头");
                owTaskDto.setImproveRequied("1.对夜间建筑施工作业的检查;\n" +
                        "2.对建筑垃圾、工程渣土产生单位申报以及委托运输情况的检查;\n" +
                        "3.对建筑垃圾、工程渣土承运单位的运输许可证以及承运的建筑垃圾、工程渣土处置证情况的检查;\n" +
                        "4.对运输建筑垃圾.工程渣土的车船运输规范的检查。");
                break;
            case 2://kitchen
                owTaskDto.setOwRegisterType("1");
                owTaskDto.setIssueContent("餐厨垃圾、废弃油脂、生活垃圾");
                owTaskDto.setImproveRequied("1.对餐厨垃圾产生单位申报以及定向收运情况的检查;\n" +
                        "2.对餐厨废弃油脂产生单位定向收运以及建立餐厨废弃油脂记录台账的检查;");
                break;
        }
        owTaskDto.setCreatemanId("1");
        owTaskDto.setCompanyId("1");
        owTaskDto.setCreateman("admin123");
        owTaskDto.setOwTaskType(OwTaskType.DoubleRandom.getKeyName());
        return owTaskService.addDataAndAssign4DoubleRandom(owTaskDto);
    }

    /**
     *
     * @return
     */
    private String getCurrentQuarter() {
        String MM = DateTool.getCurrentDateStr1("MM");
        int currentMonth = Integer.parseInt(MM);
        String quarter = null;
        if (1 <= currentMonth && currentMonth <= 3) {
            quarter = "Q1";
        } else if (4 <= currentMonth && currentMonth <= 6) {
            quarter = "Q2";
        } else if (7 <= currentMonth && currentMonth <= 9) {
            quarter = "Q3";
        } else if (10 <= currentMonth && currentMonth <= 12) {
            quarter = "Q4";
        }
        return quarter;
    }
    /**
     *
     * @return
     */
    private String getCurrentMonth() {
        String MM = DateTool.getCurrentDateStr1("MM");
        return MM;
    }

    /**
     *
     * @param total 总数
     * @param generate
     * @return
     */
    private static Set getRandomSetNotRepeat(int total,int generate){
        Set<Integer> set = new HashSet<Integer>();
        //当generate==0时，不需要循环
        if(generate==0){
            return set;
        }else{
            while (true) {
                System.out.println("难道不是整数吗："+total);
                set.add(RandomUtils.nextInt(total));
                if (set.size() == generate) {
                    for (Integer value : set) {
                        System.out.println(value);
                    }
                    return set;
                }
            }
        }


    }

    public static void main(String[] args) {
//        Set<Integer> set = new HashSet<Integer>();
//        set.add(1);
//        set.add(1);
//        set.add(5);
//        set.add(5);
//        for(Integer value : set){
//            System.out.println(value);
//        }
        Set randomSetNotRepeat = getRandomSetNotRepeat(3, 1);
        Iterator<Integer> iterator = randomSetNotRepeat.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next()+" ");
        }



    }

    /**
     * @param owrRegionId
     * @param regionName
     * @param owrEntityListInfoList
     * @param owrTmpPairList
     * @param owrTmpEntityList
     * @return
     */
    private String exeOwrTmpEntity(String year,String quarter,String month,Long owrRegionId, String regionName, List<OwrEntityListInfo> owrEntityListInfoList, List<OwrTmpPair> owrTmpPairList, List<OwrTmpEntity> owrTmpEntityList) {
        int i = 0;
        //createman作为批次标志
        String createman = DateTool.getCurrentDateStr1("yyyyMMddHHmmssSSS");
        for (OwrEntityListInfo owrEntityListInfo : owrEntityListInfoList) {
            OwrTmpPair owrTmpPair = owrTmpPairList.get(i++);
            OwrTmpEntity owrTmpEntity = new OwrTmpEntity();
            owrTmpEntity.setEntityId(owrEntityListInfo.getId().toString());
            owrTmpEntity.setEntityName(owrEntityListInfo.getEntName()+"-"+owrEntityListInfo.getEntShopName());
            owrTmpEntity.setRegionId(owrRegionId);
            owrTmpEntity.setRegionName(regionName);
            owrTmpEntity.setUserPair(owrTmpPair.getUserPair());
            owrTmpEntity.setUserNamePair(owrTmpPair.getUserNamePair());
            owrTmpEntity.setCreateman(createman);
            owrTmpEntity.setYear(year);
            owrTmpEntity.setQuarter(quarter);
            owrTmpEntity.setMonth(month);
            owrTmpEntityMapper.insert(owrTmpEntity);
            owrTmpEntityList.add(owrTmpEntity);
        }
        return createman;
    }


    /**
     * userlist to userpair list
     * @param entityCountByRegion how many group 总共有多少组
     * @param userList
     * @param owrTmpPairList
     */
    private void exePair(String year,String quarter,String month,Long owrRegionId, int entityCountByRegion, List<A2user> userList, List<OwrTmpPair> owrTmpPairList) {
        Collections.shuffle(userList);
        Collections.shuffle(userList);
        StringBuilder sbUserId = new StringBuilder();
        StringBuilder sbUserName = new StringBuilder();
        List<Integer> sbListUserId = new ArrayList<>();
        List<String> sbListUserName = new ArrayList<>();
        int i = 0;
        int j = 0;
        int pairNumber = 0;
        while (true) {
            if (i == userList.size()) {
                Collections.shuffle(userList);
                Collections.shuffle(userList);
                i = 0;
            }
            A2user user = userList.get(i);

            sbListUserId.add(user.getId());
            sbListUserName.add(user.getName());
            //the second user ,save it as a pair
            if (j % 2 == 1) {
                //sort first
                sbUserId.setLength(0);
                sbUserName.setLength(0);
                int aUserId = sbListUserId.get(0);
                int bUserId = sbListUserId.get(1);
                String aUserName = sbListUserName.get(0);
                String bUserName = sbListUserName.get(1);
                //maybe the two value is the same user when shuffle the list
                if(aUserId == bUserId){
                    System.out.println("===============================aUserId == bUserId ==================");
                    System.out.println(aUserId +"===" +bUserId);
                    Collections.shuffle(userList);
                    Collections.shuffle(userList);
                    sbUserId.setLength(0);
                    sbUserName.setLength(0);
                    sbListUserId.clear();
                    sbListUserName.clear();
                    i = 0;
                    j = 0;
                    continue;
                }
                if (aUserId < bUserId) {
                    sbUserId.append(aUserId).append(",").append(bUserId);
                    sbUserName.append(aUserName).append(",").append(bUserName);
                } else {
                    sbUserId.append(bUserId).append(",").append(aUserId);
                    sbUserName.append(bUserName).append(",").append(aUserName);
                }
                //
                OwrTmpPair owrTmpPair = new OwrTmpPair();
                owrTmpPair.setUserPair(sbUserId.toString());
                owrTmpPair.setUserNamePair(sbUserName.toString());
                owrTmpPair.setRegionId(owrRegionId);
                owrTmpPair.setYear(year);
                owrTmpPair.setQuarter(quarter);
                owrTmpPair.setMonth(month);
                owrTmpPairMapper.insert(owrTmpPair);
                owrTmpPairList.add(owrTmpPair);
                sbUserId.setLength(0);
                sbUserName.setLength(0);
                sbListUserId.clear();
                sbListUserName.clear();
                pairNumber++;
            }
            i++;
            j++;
            if (pairNumber == entityCountByRegion) {
                break;
            }
        }
    }


    @Override
    public Result<OwrTmpPairDto> pagination(OwrTmpPairDto owrTmpPairDto, PageDto pageDto) {
        //分页查询
        Result<OwrTmpPairDto> result = myPageUtils.pagination(
                owrTmpPairDto, pageDto,
                OwrTmpPair.class,
                OwrTmpPairDto.class,
                owrTmpPairMapper,
                false, null);

        return result;
    }

    /**
     * 分布查询，有数据边界控制功能
     *
     * @param owrTmpPairDto
     * @param pageDto
     * @param paramMap
     * @return
     */
    @Override
    public Result<OwrTmpPairDto> pagination(OwrTmpPairDto owrTmpPairDto, PageDto pageDto, Map<String, Object> paramMap) {
        //数据边界控制参数
        Map<String, Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<OwrTmpPairDto> result = myPageUtils.pagination(
                owrTmpPairDto, pageDto,
                OwrTmpPair.class,
                OwrTmpPairDto.class,
                owrTmpPairMapper,
                paramMap1,
                false, null);

        return result;
    }


    @Override
    public Result<OwrTmpPairDto> selectAll() {
        Result<OwrTmpPairDto> result = new Result();

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("page", pageDto);

        List<OwrTmpPair> list = owrTmpPairMapper.selectAll(mapParam);
        List<OwrTmpPairDto> dtoList = myMapper.map(list, OwrTmpPairDto.class);
        result.setResultList(dtoList);

        return result.success();
    }

    @Override
    public Result<OwrTmpPairDto> selectById(long id) {
        Result<OwrTmpPairDto> result = new Result();

        OwrTmpPair owrTmpPair = owrTmpPairMapper.selectById(id);
        OwrTmpPairDto dto = mapper.map(owrTmpPair, OwrTmpPairDto.class);
        result.setResultObj(dto);

        return result.success();
    }


    /**
     * 返回ID值
     */
    @Override
    public Result<OwrTmpPairDto> addData(OwrTmpPairDto owrTmpPairDto) {
        Result<OwrTmpPairDto> result = new Result();

        //封闭数据
        OwrTmpPair owrTmpPair = mapper.map(owrTmpPairDto, OwrTmpPair.class);
        owrTmpPair.setCreatedate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owrTmpPairMapper.insert(owrTmpPair);
        if (i == 0) {
            return result.fault("插入失败");
        }

        OwrTmpPairDto dto = mapper.map(owrTmpPair, OwrTmpPairDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
     * 返回ID值
     */
    @Override
    public Result<OwrTmpPairDto> editData(OwrTmpPairDto owrTmpPairDto) {
        Result<OwrTmpPairDto> result = new Result();

        //封装数据
        OwrTmpPair owrTmpPair = mapper.map(owrTmpPairDto, OwrTmpPair.class);
        owrTmpPair.setModifydate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owrTmpPairMapper.updateById(owrTmpPair);
        if (i == 0) {
            return result.fault("编辑数据失败");
        }

        OwrTmpPairDto dto = mapper.map(owrTmpPair, OwrTmpPairDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
     * 伪删除记录，返回ID值
     */
    @Override
    public Result deleteById(long id, String adminMan) {
        Result result = new Result();

        Map<String, Object> mapParameter = new HashMap();
        mapParameter.put("id", id);
        mapParameter.put("modifyman", adminMan);
        mapParameter.put("modifydate", DateTool.getCurTimestamp());

        //调用mapper
        long i = owrTmpPairMapper.deleteById(mapParameter);
        if (i == 0) {
            return result.fault("删除数据失败");
        }

        return result.success();
    }


    /* *//**
     * 在执行之前先检查本年度本季度是否已经执行过，如果已经执行过，把所有的记录伪删除 deleteflag=1
     * @param year
     * @param quarter
     * @param month
     * @param adminMan
     * @return
     *//*
    private Result deleteAllKitchBuilding(String year, String quarter, String month,String adminMan) {
        Result result = new Result();

        Map<String, Object> mapParameter = new HashMap();
        mapParameter.put("year", year);
        mapParameter.put("quarter", quarter);
        mapParameter.put("month", month);
        mapParameter.put("modifyman", adminMan);
        mapParameter.put("modifydate", DateTool.getCurTimestamp());

        //调用mapper
        long l1 = owrDoubleTaskPairMapper.deleteAllKitchByQuarterAndYear(mapParameter);
         if (l1 == 0) {
            return result.fault("删除 owrDoubleTaskPair数据失败");
        }

        return result.success();
    }
*/
    /**
     * 返回ID值
     */
    /*@Override
    public Result randomExecute() {
        Result<OwrTmpPairDto> result = new Result();

        List<OwrRegion> owrRegions = owrRegionMapper.selectAllRegionId();
        //工地 : owrTypeId 1,工地，2 餐厨
        for (int i = 0; i < owrRegions.size(); i++) {
            OwrRegion owrRegion = owrRegions.get(i);
            Long owrTypeId = owrRegion.getOwrTypeId();
            OwrType owrType = owrTypeMapper.selectById(owrTypeId);
            if(owrTypeId != 1){
                continue;
            }
            execute1(owrRegion, owrType);
        }

        //餐厨 : owrTypeId 1,工地，2 餐厨
        for (int i = 0; i < owrRegions.size(); i++) {
            OwrRegion owrRegion = owrRegions.get(i);
            Long owrTypeId = owrRegion.getOwrTypeId();
            OwrType owrType = owrTypeMapper.selectById(owrTypeId);
            if(owrTypeId != 2){
                continue;
            }
            Result result1 = execute2(owrRegion, owrType);
            if(!result1.isSuccess()){
                if("continue".equals(result1.getContent())){
                    continue;
                }
            }
        }

        return result.success();
    }*/

    /**
     * 在执行之前先检查本年度本月份是否已经执行过，如果已经执行过，把所有的记录伪删除 deleteflag=1
     * @param year
     * @param quarter
     * @param month
     * @param adminMan
     * @return
     */
    /*private Result deleteAllBuilding(String year, String quarter, String month,String adminMan) {
        Result result = new Result();

        Map<String, Object> mapParameter = new HashMap();
        mapParameter.put("year", year);
        mapParameter.put("quarter", quarter);
        mapParameter.put("month", month);
        mapParameter.put("modifyman", adminMan);
        mapParameter.put("modifydate", DateTool.getCurTimestamp());

        //调用mapper
        long l1 = owrDoubleTaskPairMapper.deleteAllBuildingByQuarterAndYear(mapParameter);

        if (l1 == 0) {
            return result.fault("删除 owrDoubleTaskPair数据失败");
        }
        return result.success();
    }*/

}
